package data

import (
	"context"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/google/uuid"
	"hello-kratos/kratos-server/internal/biz"
	"hello-kratos/kratos-server/internal/data/ent/user"
	"strings"
	"time"
)

/*
curd示例: https://github.com/go-kratos/examples/tree/main/blog
*/
type userRepo struct {
	data *Data
	log  *log.Helper
}

func NewUserRepo(data *Data, logger log.Logger) biz.UserRepo {
	return &userRepo{
		data: data,
		log:  log.NewHelper(logger),
	}
}

func (r *userRepo) Save(ctx context.Context, u *biz.User) error {
	_, err := r.data.mysql.client.User.Create().
		SetAccount("KU" + strings.ReplaceAll(time.Now().Format("20060102150405.000"), ".", "")).
		SetUsername(u.UserName).
		SetPassword(u.PassWord).
		SetNickname(u.NickName).
		SetAge(u.Age).
		SetGender(user.Gender(u.Gender)).
		SetRemark(u.Remark).
		Save(ctx)
	if err != nil {
		return err
	}
	return nil
}

func (r *userRepo) Update(ctx context.Context, u *biz.User) error {
	id, _ := uuid.FromBytes([]byte(u.Id))
	_, err := r.data.mysql.client.User.Get(ctx, id)
	if err != nil {
		return err
	}
	return nil
}

func (r *userRepo) FindByID(ctx context.Context, id string) (*biz.User, error) {
	uid, _ := uuid.FromBytes([]byte(id))
	u, err := r.data.mysql.client.User.Get(ctx, uid)
	if err != nil {
		return nil, err
	}
	return &biz.User{
		Id:       u.ID.String(),
		Account:  u.Account,
		UserName: u.Username,
		PassWord: u.Password,
		NickName: u.Nickname,
		Age:      u.Age,
		Gender:   u.Gender.String(),
		Remark:   u.Remark,
	}, nil
}

func (r *userRepo) FindByAccount(ctx context.Context, account string) (*biz.User, error) {
	u, err := r.data.mysql.client.User.Query().Where(user.Account(account)).Only(ctx)
	if err != nil {
		return nil, err
	}
	return &biz.User{
		Id:       u.ID.String(),
		Account:  u.Account,
		UserName: u.Username,
		PassWord: u.Password,
		NickName: u.Nickname,
		Age:      u.Age,
		Gender:   u.Gender.String(),
		Remark:   u.Remark,
	}, nil
}

func (r *userRepo) FindForLogin(ctx context.Context, u *biz.User) (*biz.User, error) {
	only, err := r.data.mysql.client.User.Query().Where(user.Username(u.UserName), user.Password(u.PassWord)).Only(ctx)
	if err != nil {
		return nil, err
	}
	return &biz.User{
		Id:       only.ID.String(),
		Account:  only.Account,
		UserName: only.Username,
		PassWord: only.Password,
		NickName: only.Nickname,
		Age:      only.Age,
		Gender:   only.Gender.String(),
		Remark:   only.Remark,
	}, nil
}
